package com.huzz.security.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huzz.security.entity.*;
import com.huzz.security.mapper.*;
import com.huzz.security.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
* 系统用户-业务实现层
*
* @author 童年的纸飞机
* @since 2023-01-12 14:07
*/
@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    /**
     * 系统用户Mapper
     */
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysPermissionMapper permissionMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysRolePermissionMapper rolePermissionMapper;


    @Override
    public SysUser getByUsername(String username) {
        return sysUserMapper.selectOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, username));
    }

    @Override
    public List<GrantedAuthority> getUserAuthorityInfo(Integer userId) {
        List<GrantedAuthority> authorities = new ArrayList<>();

        List<SysUserRole> userRoleList = userRoleMapper.selectList(Wrappers.<SysUserRole>lambdaQuery().eq(SysUserRole::getUserId, userId));
        for (SysUserRole userRole : userRoleList) {
            SysRole role = roleMapper.selectById(userRole.getRoleId());
            if (role != null) {
                authorities.add(new SimpleGrantedAuthority(role.getName()));
                List<SysRolePermission> rolePermissionList = rolePermissionMapper.selectList(Wrappers.<SysRolePermission>lambdaQuery().eq(SysRolePermission::getRoleId, role.getId()));
                for (SysRolePermission rolePermission : rolePermissionList) {
                    SysPermission permission = permissionMapper.selectById(rolePermission.getPermissionId());
                    if (permission != null) {
                        authorities.add(new SimpleGrantedAuthority(permission.getName()));
                    }
                }
            }

        }
        return authorities;
    }
}